package com.sais.manage.boot.building.asy;

import com.sais.manage.boot.building.dto.RoomDTO;
import com.sais.manage.boot.building.mapper.RoomMapper;
import com.sais.manage.boot.platform.dto.UserDTO;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 宿舍管理平台-批量绑定宿舍学生
 *
 * @author zwp
 * @date 2020/2/13
 */
@Component
public class BatchBindRoomUser {

    @Resource
    private RoomMapper roomMapper;

    /**
     * 批量绑定宿舍 学生
     *
     * @param rooms 待分配宿舍集合
     * @param users 待分配学生
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public boolean batchBindRoomUser(List<RoomDTO> rooms, List<UserDTO> users) {
        int userCount = 0;
        int roomCount = 0;
        while (userCount < users.size() && roomCount < rooms.size()) {
            RoomDTO room = rooms.get(roomCount);
            String roomId = room.getUkId();
            Integer availCount = room.getBuildingType() - room.getCount();

            for (int i = 0; i < availCount && userCount <users.size(); i++) {
                String userId = users.get(userCount).getUkId();
                roomMapper.bindRoomUser(userId, roomId);
                roomMapper.updateCount(roomId,room.getCount() + i + 1);
                userCount++;
            }

            roomCount++;

        }
        return true;
    }
}
